#coding=utf-8
"""
server入口模块
"""
import os.path
import time
from datetime import date, datetime
from decimal import Decimal
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from jsonpickle import handlers as JsonHandlers
from tornado_json.routes import get_routes
from tornado_json.application import Application
from tornroutes import route
from react.conf import settings
from . import models
from . import api
from .tools import Session, Base
from .handlers import HomeHandler

define("port", default=8989, help="run on the given port", type=int)
define("render", default=True, help="server side render", type=bool)

#DEBUG = False
settings.configure(
	RENDER=options.render,
    RENDER_URL='http://127.0.0.1:8990/render',
)

class MyDateHandler(JsonHandlers.BaseHandler):
    """
    注册日期特别处理
    """
    def flatten(self, obj, data):
        return int(time.mktime(obj.timetuple())*1000)

    def restore(self, obj):
        #t = time.localtime(data/1000)
        #return datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, )\
        return datetime.fromtimestamp(obj/1000)


class MyDecimalHandler(JsonHandlers.BaseHandler):
    def flatten(self, obj, data):
        return float(obj)

    def restore(self, obj):
        return Decimal.from_float(obj)

JsonHandlers.register(date, MyDateHandler)
JsonHandlers.register(datetime, MyDateHandler)
JsonHandlers.register(datetime, MyDateHandler)
JsonHandlers.register(Decimal, MyDecimalHandler)

class MyApplication(Application):
    def __init__(self):
        routes = get_routes(api)
        routes.extend(route.get_routes())
        routes.extend([
            (r"/.*", HomeHandler),
        ])
        print(routes)
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "./templates"),
            static_path=os.path.join(os.path.dirname(__file__), "../dist"),
            cookie_secret='liubin',
            login_url='/login',
            #xsrf_cookies=True
            debug=True
        )
        Application.__init__(self, routes, settings, Session)


def main():
    # 配置logging等级在debug
    tornado.options.options.logging = "debug"
    tornado.options.parse_command_line()
    #tornado.options.print_help()
    http_server = tornado.httpserver.HTTPServer(MyApplication())
    print('server start at ' + str(options.port) )
    print('please press ctrl + break to stop server')
    http_server.listen(options.port)
    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()


if __name__ == '__main__':
    main()
